/*
 * File: DataConnection.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package foxtrotbravo;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.google.appengine.api.rdbms.AppEngineDriver;

/**
 * The Class DataConnection.
 */
public class DataConnection
{

    /** The connection. */
    private static Connection connection = null;

    /**
     * Connect.
     * 
     * @return true, if successful
     */
    public static boolean connect()
    {
        try
        {
            if (connection == null || !connection.isValid(10))
            {
                try
                {
                    connectToDb(
                            new AppEngineDriver(),
                            "jdbc:google:rdbms://dominionenterprises.com:triperest:foxtrotbravo/foxtrotbravo");
                    if (!connection.isValid(10))
                        throw new RuntimeException("Database Error");
                    return true;
                } catch (SQLException e)
                {
                    if (Config.isDev())
                    {
                        try
                        {// If we can't connect to google, try mysql
                            connectToDb(new com.mysql.jdbc.Driver(),
                                    "jdbc:mysql://localhost:3306/foxtrotbravo?user=root&password=");
                            if (!connection.isValid(10))
                                throw new RuntimeException("Database Error");
                            return true;
                        } catch (SQLException e2)
                        {
                            throw new RuntimeException(e2);
                        }
                    }
                    throw new RuntimeException(e);
                }
            }
        } catch (SQLException e1)
        {
            throw new RuntimeException(e1);
        }
        try
        {
            if (!connection.isValid(10))
            {
                throw new RuntimeException("Database Error");
            }
            return true;
        } catch (SQLException e)
        {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * Connect to db.
     * 
     * @param driver
     *            the driver
     * @param connectionString
     *            the connection string
     * @throws SQLException
     *             the sQL exception
     */
    private static void connectToDb(Driver driver, String connectionString)
            throws SQLException
    {
        DriverManager.registerDriver(driver);
        connection = DriverManager.getConnection(connectionString);
    }

    /**
     * Get Connection.
     * 
     * @return the connection
     */
    public static Connection getConnection()
    {
        if (connection == null)
            connect();
        return connection;
    }

}
